using System;
using System.Data.Entity;
using System.Reflection;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using YiCheap.Core.Data;
using YiCheap.Core.Infrastructure;
using YiCheap.Core.Infrastructure.DependencyManagement;
using YiCheap.Data;
using YiCheap.Service.Localization;

namespace YiCheap.Web
{
    public class YiCheapEngine : IEngine
    {


        private ContainerManager _containerManager;


        public ContainerManager ContainerManager
        {
            get { return _containerManager; }
        }


        public YiCheapEngine()
        {
          

        }
     


        public void Initialize()
        {
            //var connstr = ConfigurationManager.ConnectionStrings["pbConnectionString"].ToString();
            var builder = new ContainerBuilder();

            //db
            builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerHttpRequest();
            builder.Register<DbContext>(c => new YiCheapContext()).InstancePerHttpRequest();


            ////service
            builder.RegisterType<LocalizationService>().As<ILocalizationService>();



            //controller
            builder.RegisterControllers(Assembly.GetExecutingAssembly());


            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            
            _containerManager = new ContainerManager(container);

  
        }

        public T Resolve<T>() where T : class
        {
            return ContainerManager.Resolve<T>();
        }

        public object Resolve(Type type)
        {
            return ContainerManager.Resolve(type);
        }

        public T[] ResolveAll<T>()
        {
            return ContainerManager.ResolveAll<T>();
        }
    }
}